<?php

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die;

jimport('joomla.application.component.model');

class ApkipasModelDetail extends JModel
{

	function getData($ordering = NULL) {

		$user = &JFactory::getUser();
		$db = &JFactory::getDBO();

		$app = &JFactory::getApplication();
		$params =  &$app->getParams('com_apkipas');
		
		$id = JRequest::getInt('id');
		
		$query = 'SELECT a.id as title_id ,
							a.product_id, 
							a.title as main_title, 
							a.alias, a.created_date, 
							a.meta_title ,
							b.* 
					FROM #__apkipas_titles as a
					LEFT JOIN #__apkipas_resources as b ON a.product_id = b.id ';
					
		$where = array();
		$where[] = 'a.published = 1';
		if($id != 0){
			$where[] = ' a.id = '.$id;
		}
		
		if(count($where) > 0) {
			$query .= ' WHERE '.implode(' AND ', $where);
		}
		
		$db->setQuery($query);
		$rows = $db->loadObject();
		return $rows;
	}
	
	function getTags($ordering = NULL) {
	
		$user = &JFactory::getUser();
		$db = &JFactory::getDBO();
	
		$app = &JFactory::getApplication();
		$params =  &$app->getParams('com_apkipas');
	
		$tag = JRequest::getVar('tag');
		$tag = str_ireplace(':', '-', $tag);
		$limitstart = JRequest::getInt('limitstart');
		
		$query = 'SELECT r.id as resource_id FROM #__apkipas_tags as a 
					LEFT JOIN #__apkipas_refs as b ON a.id = b.tagid 
					LEFT JOIN #__apkipas_resources as r ON b.id = r.itune_id
					WHERE a.alias = "'.$tag.'"';
		
		$query = 'SELECT b.id FROM apkipas_apkipas_tags as a
		LEFT JOIN apkipas_apkipas_refs as b ON a.id = b.tagid
		WHERE a.alias = "'.$tag.'"';

		$db->setQuery($query);
		$rows = $db->loadObjectList();
		$arr_resources = array();
		foreach ($rows as $row){
			$arr_resources[] = $row->id;
		}
		$tmp_resources  = implode(',',$arr_resources);
	
		$query = 'SELECT r.id as resource_id FROM #__apkipas_resources as r 
				WHERE r.itune_id IN ('.$tmp_resources.')';
		$db->setQuery($query);
		$rows = $db->loadObjectList();
		
		unset($arr_resources);
		$arr_resources = array();
		
		if(count($rows) > 0){
			foreach ($rows as $row){
				$arr_resources[] = $row->resource_id;
			}
			
			$tmp_resources  = implode(',',$arr_resources);
			
			$query = 'SELECT a.id as title_id ,
							a.product_id,
							a.title as main_title,
							a.alias, a.created_date,
							a.meta_title ,
							b.des,
							b.category,
							b.meta_des ,b.bg
					FROM #__apkipas_titles as a
					LEFT JOIN #__apkipas_resources as b ON a.product_id = b.id ';
			
			$where = array();
			$where[] = 'a.published = 1';
			$where[] = 'a.product_id IN ( '.$tmp_resources.') ';
			
			if(count($where) > 0) {
				$query .= ' WHERE '.implode(' AND ', $where);
			}
			$query .= ' ORDER BY title_id DESC ';
			
			$db->setQuery($query, $limitstart, 10);
			$rows = $db->loadObjectList();
			return $rows;
		}else{
			return null;
		}
	}

}
